package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.MobileLoginBody;
import com.ruoyi.common.core.domain.model.MobileSmsLoginBody;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author sungangbin
 */
@Api(value = "登录操作管理",tags = "登录操作模块接口")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("用户登录接口：（token：authorization令牌）")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),loginBody.getLoginSource());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



    @ApiOperation("移动端用户登录接口-一键登录-匿名")
    @PostMapping("/mobileLogin")
    @Anonymous
    public AjaxResult mobileLogin(@RequestBody MobileLoginBody  mobileLoginBody)
    {
        logger.info("移动端用户登录接口-一键登录-匿名入参:{}",mobileLoginBody);

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        Map<String,Object>  result = null;
        try {
            result = loginService.mobileLogin(mobileLoginBody.getEncryptedData(), mobileLoginBody.getIv(), mobileLoginBody.getCode(),mobileLoginBody.getParentCustomerUuid(),mobileLoginBody.getCustomerId());
        } catch (Exception e) {
            ajax = AjaxResult.error(e.getMessage());
            logger.info("移动端用户登录接口-一键登录-匿名出参:{}",ajax);
            return ajax;
        }
        ajax.put(Constants.TOKEN, result.get(Constants.TOKEN));
//        ajax.put(Constants.OPENID, result.get(Constants.OPENID));
        logger.info("移动端用户登录接口-一键登录-匿名出参:{}",ajax);
        return ajax;
    }

    @ApiOperation("移动端用户退出登录接口-请求头中添加Authorization参数即可")
    @PostMapping("/mobileLogout")
    public AjaxResult mobileLogout(@RequestHeader("Authorization") String token)
    {
        logger.info("移动端用户退出登录接口-匿名入参:{}",token);
        AjaxResult ajax = AjaxResult.success();
        tokenService.invalidateToken(token);
        logger.info("移动端用户退出登录接口-匿名出参:{}",ajax);
        return ajax;
    }


    @ApiOperation("移动端用户登录接口-短信验证码登录-匿名")
    @PostMapping("/mobileSmsLogin")
    @Anonymous
    public AjaxResult mobileSmsLogin(@RequestBody MobileSmsLoginBody mobileSmsLoginBody)
    {
        logger.info("移动端用户登录接口-短信验证码登录-匿名入参:{}",mobileSmsLoginBody);
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        Map<String,Object>  result = null;
        try {
            result = loginService.mobileSmsLogin(mobileSmsLoginBody.getMobilePhoneNumber(), mobileSmsLoginBody.getSmsCode(),mobileSmsLoginBody.getCode(),mobileSmsLoginBody.getParentCustomerUuid(),mobileSmsLoginBody.getCustomerId());
            if(StringUtils.isNotNull(result.get("msg"))){
                ajax = AjaxResult.error((String)result.get("msg"));
            }else{
                ajax.put(Constants.TOKEN, result.get(Constants.TOKEN));
            }
        } catch (Exception e) {
            logger.info("移动端用户登录接口-短信验证码登录-匿名报错信息:{}",e.getMessage());
            ajax = AjaxResult.error("小程序登录失败！！");
        }
        logger.info("移动端用户登录接口-短信验证码登录-匿名出参:{}",ajax);
        return ajax;
    }


    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation("获取用户信息接口：（user:用户信息，roles：角色信息，permissions：权限信息）")
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
